package service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import model.Tinventory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import dao.InventoryDaoI;
import pageModel.DataGrid;
import pageModel.Inventory;
import service.InventoryServiceI;
@Service("inventoryService")
public class InventoryServiceImpl implements InventoryServiceI {
private InventoryDaoI inventoryDao;

	public InventoryDaoI getInventoryDao() {
	return inventoryDao;
}
@Autowired
public void setInventoryDao(InventoryDaoI inventoryDao) {
	this.inventoryDao = inventoryDao;
}

	@Override
	public DataGrid datagrid(Inventory inventory) {
		DataGrid dg=new DataGrid();
		String hql="from Tinventory t where 1=1";
		Map<String,Object> params=new HashMap<String,Object>();
		hql = addWhere(inventory, hql, params);
		String totalHql="select count(*) "+hql;
		if(inventory.getSort()!=null){
		hql+=" order by "+inventory.getSort()+" "+inventory.getOrder();
		}
		List<Tinventory> lt=inventoryDao.find(hql,params,inventory.getPage(),inventory.getRows());
		List<Inventory> l=new ArrayList<Inventory>();
		if(lt!=null&&lt.size()>0){
			for(Tinventory t :lt){
				Inventory i=new Inventory();
				BeanUtils.copyProperties(t, i);
				if(t.getTgood()!=null){
					i.setCode(t.getTgood().getCode());
					i.setName(t.getTgood().getName());
					i.setUnit(t.getTgood().getUnit());
				}
				l.add(i);
			}
		}
		dg.setTotal(inventoryDao.count(totalHql,params));
		dg.setRows(l);
		return dg;
	}
	private String addWhere(Inventory inventory, String hql, Map<String, Object> params) {
		if(inventory.getCode()!=null&&!inventory.getCode().trim().equals("")){
		hql+=" and t.tgood.code like :code";
		params.put("code", "%%"+inventory.getCode()+"%%");
		}
		if(inventory.getName()!=null&&!inventory.getName().trim().equals("")){
			hql+=" and t.tgood.name like :name";
			params.put("name", "%%"+inventory.getName()+"%%");
			}
		return hql;
	}
	@Override
	public void edit(Inventory inventory) {
		Tinventory t=inventoryDao.get(Tinventory.class, inventory.getId());
		BeanUtils.copyProperties(inventory , t);
	}

}
